const { ipcRenderer, clipboard, nativeImage, remote, screen, desktopCapturer } = require('electron')
const qs = require('querystring');

const search = qs.parse(location.search.split('?').pop());
const { CaptureEditor } = require('./capture-editor')
const { getCurrentScreen } = require('./utils')

const $canvas = document.getElementById('js-canvas')
const $bg = document.getElementById('js-bg')
const $sizeInfo = document.getElementById('js-size-info')
const $toolbar = document.getElementById('js-toolbar')

const $btnClose = document.getElementById('js-tool-close')
const $btnOk = document.getElementById('js-tool-ok')
const $btnReset = document.getElementById('js-tool-reset')

const currentScreen = getCurrentScreen();
const getScreenSources = ({}, callBack) => {
    const thumbSize = {
        width: parseInt(search.width) * window.devicePixelRatio,
        height: parseInt(search.height) * window.devicePixelRatio
    };
    console.time('renderer1:' + search.display_id);
    console.time('renderer2:' + search.display_id);
    desktopCapturer.getSources({ types: ['screen'], thumbnailSize: thumbSize}).then(async sources => {
        console.timeEnd('renderer2:' + search.display_id);
        sources.forEach(source => {
            if (source.display_id.toString() === search.display_id.toString()) {
                try {
                    console.time('renderer3:' + search.display_id);
                    const dataUrl = source.thumbnail.toDataURL();
                    console.timeEnd('renderer3:' + search.display_id);
                    callBack && callBack(dataUrl);
                    ipcRenderer.send('show-capture-renderer', source.display_id);
                    console.timeEnd('renderer1:' + search.display_id);
                } catch (e) {
                    console.log(e);
                }
            }
        });
    });
};

const takeScreenShot = ({}, callback) => {
    let width = parseInt(search.width) * window.devicePixelRatio;
    let height = parseInt(search.height) * window.devicePixelRatio;
    let screenConstraints = {
        mandatory: {
            chromeMediaSource: "desktop", // desktop screen
            // chromeMediaSourceId: sources[i].id,
            // chromeMediaSourceId: `screen:${search.display_id || ''}`,
            chromeMediaSourceId: `screen:${search.display_id}:0`,
            minWidth: width,
            maxWidth: width,
            minHeight: height,
            maxHeight: height
        },
        optional: []
    };

    let session = {
        audio: false,
        video: screenConstraints
    };

    let streaming = false;
    let canvas = document.createElement("canvas");
    let video = document.createElement("video");
    video.style.cssText = 'position:absolute;top:-10000px;left:-10000px;'
    document.body.appendChild(canvas);
    document.body.appendChild(video);

    // loadedmetadata
    video.addEventListener("canplay", function(){
        if (!streaming) {
            video.setAttribute("width", width.toString());
            video.setAttribute("height", height.toString());
            canvas.setAttribute("width", width.toString());
            canvas.setAttribute("height", height.toString());
            streaming = true;

            let context = canvas.getContext("2d");

            if (width && height) {
                canvas.width = width;
                canvas.height = height;
                context.drawImage(video, 0, 0, width, height);

                video.pause();
                video.src = "";
                console.timeEnd('renderer2:');
                callback && callback(canvas.toDataURL('image/png'));
                document.body.removeChild(video);
                document.body.removeChild(canvas);
                ipcRenderer.send('show-capture-renderer-all');
            }
        }
    }, false);

    console.time('renderer1:');
    console.time('renderer2:');
    navigator.mediaDevices.getUserMedia(session).then(stream => {
        console.timeEnd('renderer1:');
        video.srcObject = stream;
        video.play();
    }).catch(err => {
        console.error("Can't take a screenshot", err);
    })
};

const screenCallbak = (imgSrc) => {
    let capture = new CaptureEditor($canvas, $bg, imgSrc)

    let onDrag = (selectRect) => {
        $toolbar.style.display = 'none'
        $sizeInfo.style.display = 'block'
        $sizeInfo.innerText = `${selectRect.w} * ${selectRect.h}`
        if (selectRect.y > 35) {
            $sizeInfo.style.top = `${selectRect.y - 30}px`
        } else {
            $sizeInfo.style.top = `${selectRect.y + 10}px`
        }
        $sizeInfo.style.left = `${selectRect.x}px`
    }
    capture.on('start-dragging', onDrag)
    capture.on('dragging', onDrag)

    let onDragEnd = () => {
        if (capture.selectRect) {
            ipcRenderer.send('capture-screen', {
                type: 'select',
                screenId: currentScreen.id,
            })
            const {
                r, b,
            } = capture.selectRect
            $toolbar.style.display = 'flex'
            $toolbar.style.top = `${b + 15}px`
            $toolbar.style.right = `${window.screen.width - r}px`
        }
    }
    capture.on('end-dragging', onDragEnd)

    ipcRenderer.on('capture-screen', (e, { type, screenId }) => {
        if (type === 'select') {
            if (screenId && screenId !== currentScreen.id) {
                capture.disable()
            }
        }
    })

    capture.on('reset', () => {
        $toolbar.style.display = 'none'
        $sizeInfo.style.display = 'none'
    })

    $btnClose.addEventListener('click', () => {
        ipcRenderer.send("capture-close");
    })

    $btnReset.addEventListener('click', () => {
        capture.reset()
    })

    let selectCapture = () => {
        if (!capture.selectRect) {
            return
        }
        let url = capture.getImageUrl()
        remote.getCurrentWindow().hide();
        clipboard.writeImage(nativeImage.createFromDataURL(url))
        ipcRenderer.send('capture-screen', {
            type: 'complete',
            url
        });
    }
    $btnOk.addEventListener('click', selectCapture)

    window.addEventListener('keypress', (e) => {
        if (e.code === 'Enter') {
            selectCapture()
        }
    })
};

// 右键取消截屏
document.body.addEventListener('mousedown', (e) => {
    if (e.button === 2) {
        ipcRenderer.send("capture-close");
    }
}, true)

if (search.type_val === '1') {
    getScreenSources({}, screenCallbak);
}
if (search.type_val === '2') {
    takeScreenShot({}, screenCallbak);
}

